#!/bin/bash

# Crawl4AI 简化版本启动脚本
# 只包含最基本的功能，无复杂依赖

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 打印函数
print_status() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

print_header() {
    echo -e "${GREEN}🚀 Crawl4AI 简化版本启动${NC}"
    echo "=================================="
}

# 主函数
main() {
    print_header
    
    # 检查Python环境
    if ! command -v python &> /dev/null; then
        print_error "Python not found. Please install Python 3.8+"
        exit 1
    fi
    
    # 检查虚拟环境
    if [[ -z "${VIRTUAL_ENV}" ]]; then
        print_warning "Virtual environment not detected. Consider activating one."
    fi
    
    # 加载环境变量
    if [ -f .env ]; then
        print_status "Loading environment variables from .env"
        export $(cat .env | grep -v '^#' | xargs)
    else
        print_warning ".env file not found. Using default values."
    fi
    
    # 设置默认值
    export DEBUG=${DEBUG:-true}
    export HOST=${HOST:-0.0.0.0}
    export PORT=${PORT:-8002}
    export LOG_LEVEL=${LOG_LEVEL:-DEBUG}
    export DATA_DIR=${DATA_DIR:-data}
    
    # 检查基本依赖
    print_status "Checking dependencies..."
    if ! python -c "import fastapi, uvicorn, pydantic" 2>/dev/null; then
        print_error "Missing required dependencies. Please run: pip install fastapi uvicorn pydantic"
        exit 1
    fi
    
    # 设置JSON存储
    print_status "Setting up JSON storage..."
    mkdir -p "$DATA_DIR"
    print_status "JSON storage directory created: $DATA_DIR"
    
    # 启动服务器
    print_status "Starting simple development server..."
    print_status "Server will be available at: http://$HOST:$PORT"
    print_status "API documentation: http://$HOST:$PORT/api/docs"
    print_status "Press Ctrl+C to stop the server"
    
    # 启动应用
    python -m uvicorn app.main_simple:app \
        --host "$HOST" \
        --port "$PORT" \
        --reload \
        --log-level "$(echo $LOG_LEVEL | tr '[:upper:]' '[:lower:]')"
}

# 错误处理
trap 'print_error "Script interrupted"; exit 1' INT TERM

# 运行主函数
main "$@"
